/*if (typeof(Storage)!=="undefined") {
	if (typeof(localStorage.pkmn)==="undefined") {
		document.write("It is set.");
		localStorage.pkmn="002";
	} else
		document.write(localStorage.pkmn);
}*/
//JSON.stringify(object);
//JSON.parse(retrievedobject); setItem, getItem

function getMouse(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
		x: evt.clientX - rect.left,
		y: evt.clientY - rect.top
	};
}

function keyPress(e) {
	vtext = e.charCode;
}

function unit()
{
	this.id = arguments[0];
	this.type = arguments[1];
	this.name = arguments[2];
	this.x = arguments[3];
	this.y = arguments[4];
	
	this.reset = function() {
		this.x = 320;
		this.y = 240;
	};
};

//main game.js

var canvas;
var ctx;
var tex;
var player;
var arr;
var upd;
var mx;
var my;
var vtext;
var aMove;
var wMove;
var dMove;
var sMove;

var avg;
var avg_cnt;

function firstTime() {
	//set first time vars
	//localStorage.visited = "true";
}

function init() {
	canvas = document.getElementById("gameView");
	ctx = canvas.getContext("2d");
	canvas.addEventListener('mousemove', function(evt) {
		mouse(getMouse(canvas, evt));
	}, false);
	window.addEventListener('keypress', keyPress, false);
	tex = new Image();
	tex.src = "media/texture.png";
	player = new unit(0, "Player character", "Robert", 320, 240);
	arr = new Array();
	for (var v = 0; v < 21; v++)
		arr[v] = 0;
	upd = 0;
	avg = 0;
	avg_cnt = 0;
	mx = 150;
	my = 100;
	vtext = "null";
	aMove = true;
	wMove = true;
	dMove = true;
	sMove = true;
	
	if (typeof(localStorage.visited)==="undefined") {
		firstTime();
	} else {
	}
}

function logic() {
	var FPS = 60;
	var loop = function() {
		update();
		draw();
		setTimeout(loop, 1000/FPS);	
	};
	setTimeout(loop, 1000/FPS);	
}

function mouse(m) {
	mx = m.x-100;
	my = m.y-200;
}

function update() {
	
	if (upd==4) {
		arr.shift();
		var v = Math.floor(Math.random()*(new Date().getTime()))%10000;
		avg += v; 
		avg_cnt++;
		arr.push(v);
		upd=0;
	} else
		upd++;
	
	if (keydown.a) {
		player.x-=4;
	}
	if (keydown.w) {
		player.y-=4;
	}
	if (keydown.d) {
		player.x+=4;
	}
	if (keydown.s) {
		player.y+=4;
	}
	if (keydown.e) {
		player.reset();
	}
}

function draw() {
	ctx.clearRect(0, 0, 640, 480);
	ctx.drawImage(tex, 0, 0, 16, 16, player.x, player.y, 64, 64);
	ctx.strokeRect(mx, my, 200, 360);
	ctx.beginPath();
	ctx.moveTo(mx, my+40);
	ctx.lineTo(mx+200, my+40);
	for (var i = 1; i < 21; i++) {
		ctx.moveTo(mx+i*10-10, my+40-(40/(10000/arr[i-1])));
		ctx.lineTo(mx+i*10, my+40-(40/(10000/arr[i])));
	}
	ctx.stroke();
	ctx.moveTo(0, 0);
	ctx.fillText("Total\t\t"+avg, mx+5, my+54);
	ctx.fillText("Avg\t\t\t\t"+Math.floor(avg/avg_cnt), mx+5, my+68);
	ctx.fillText("{ mousemove }", mx+5, my+82);
	ctx.fillText(vtext, mx+5, my+96);
}
